/**
 * Created by LMN on 2017/1/10.
 */
var appIndex = angular.module('app', ['ngRoute'])
    .config(['$routeProvider', function($routeProvider){
        $routeProvider.when('/file', {//网盘
            templateUrl: 'template-file.html',
            controller:  'fileController',
            activeSideTab: 'file'
        });
        $routeProvider.when('/offline', {//离线
            templateUrl: 'template-offline.html',
            controller:  'offlineController',
            activeSideTab: 'offline'
        });
        $routeProvider.when('/transcode', {//转码
            templateUrl: 'template-transcode.html',
            controller:  'transcodeController',
            activeSideTab: 'transcode'
        });
        $routeProvider.when('/live', {//转码
            templateUrl: 'template-live.html',
            controller:  'liveController',
            activeSideTab: 'live'
        });
        $routeProvider.when('/createOfflineBt/:file', {//离线
            templateUrl: 'template-create-offline-bt.html',
            controller:  'createOfflineBtController',
            activeSideTab: 'createOffline'
        });
        $routeProvider.when('/createOfflineMagnet', {//离线
            templateUrl: 'template-create-offline-magnet.html',
            controller:  'createOfflineMagnetController',
            activeSideTab: 'createOffline'
        });
        $routeProvider.otherwise({
            redirectTo: '/file'
        });
    }]).config(function ($httpProvider) {
        $httpProvider.interceptors.push(function () {
            return {
                response: function(response){
                    if(response.data.error) erroralert(response.data.errmsg);
                    else return response;
                }
            }
        })
    });

appIndex.controller('navbarController', function ($scope, $http, $location, $route) {
    $scope.$route = $route;
});

appIndex.controller('fileController', function($scope, $http){
    $scope.list= [];
    $scope.searchList = [];
    //搜索
    $('#search_file').keydown(function (event) {
        if(event.keyCode===13 && $scope.searchName){
            $http.get('/files/search/'+$scope.searchName).success(function (msg) {
                $scope.searchList = msg;
            }).error(function (e) {
                erroralert(e.result)
            })
        }
    });
    //剪贴板
    $scope.cutBord = false;
    $scope.startMove = function () {
        var files = [];
        $.each($scope.list, function (i, e) {
            if(e.checked) files.push(e.name)
        });
        $http.post('/files/clipboard',{type: 1, files: files}).success(function () {
            $scope.cutBord = true;
        }).error(function (e) {
            erroralert(e.result);
        })
    };
    $scope.startCopy = function () {
        var files = [];
        $.each($scope.list, function (i, e) {
            if(e.checked) files.push(e.name)
        });
        $http.post('/files/clipboard',{type: 0, files: files}).success(function () {
            $scope.cutBord = true;
        }).error(function (e) {
            erroralert(e.result);
        })
    };
    $scope.paste = function () {
        $http.post('/files/paste',{type: -1}).success(function () {
            $scope.cutBord = false;
            $scope.refresh();
        }).error(function (e) {
            erroralert(e.result);
        })
    };
    //重命名
    $scope.rename_able = function () {
        var _check_count = 0;
        $.each($scope.list, function (i, e) {
            if(e.checked) _check_count++;
        });
        return _check_count == 1;
    };
    $scope.startRename = function () {
        $.each($scope.list, function (i, e) {
            if(e.checked) {
                e.renaming = true;
                e.newName = e.name;
            }
        })
    };
    $scope.rename = function (x) {
        x.renaming = false;
        $http.put('/files/'+x.name,{newName: x.newName}).success(function () {
            $scope.refresh();
        }).error(function (e) {
            erroralert(e.result);
        })
    };
    //全选和选择
    $scope.checkedAll = false;
    $scope.checkAll = function () {
        if($scope.checkedAll){
            $scope.checkedAll = true;
            $.each($scope.list, function (i, e) {
                e.checked = true;
            })
        }else{
            $scope.checkedAll = false;
            $.each($scope.list, function (i, e) {
                e.checked = false;
            })
        }
    };
    //删除文件
    $scope.deletable = function () {
        var _deletable = false;
        $.each($scope.list, function (i, e) {
            if(e.checked) _deletable = true;
        });
        return !_deletable;
    };
    $scope.delete = function () {
        confirmOut('删除这些文件？删除的文件无法恢复！', function () {
            var dir = '';
            $.each($scope.list, function (i, e) {
                if(!e.checked) return;
                dir += $scope.dir + ','+ e.name+';';
            });
            $http.delete('/files/'+dir).success(function () {
                $scope.refresh();
            }).error(function (e) {
                erroralert(e.result);
            })
        })
    };
    //新建文件夹
    var addFolderTr = $('#addFolderTr');
    $scope.newFolderName = '';
    $scope.startAddFolder = function () {
        $scope.newFolderName='新建文件夹';
        addFolderTr.show();
        addFolderTr.find('input').focus();
    };
    $scope.addNewFolder = function () {
        if(!$scope.newFolderName) return;
        addFolderTr.hide();
        $http.post('/files/mkdir',{name: $scope.newFolderName}).success(function () {
            $scope.newFolderName = '';
            $scope.refresh();
        }).error(function (e) {
            erroralert(e.result);
        });
    };
    $scope.cancelNewFolder = function () {
        $scope.newFolderName = '';
        addFolderTr.hide();
    };
    //显示目录文件
    $scope.dir = '';
    $scope.sortname = 'name';
    $scope.sortorder = 'desc';
    $scope.changeSort = function (name) {
        if($scope.sortname==name){
            if($scope.sortorder=='asc') $scope.sortorder='desc';
            else $scope.sortorder = 'asc';
        }else{
            $scope.sortname = name;
            $scope.sortorder = 'desc';
        }
        $scope.refresh();
    };
    //打开文件夹
    var makeDir = function () {
        var dirs = $scope.dir.split(',');
        var result = [], _dir = '';
        for(var i=0,l=dirs.length;i<l;i++){
            if(!dirs[i]) continue;
            _dir += dirs[i] + ',';
            result.push({
                name: dirs[i],
                dir: _dir.substring(0,_dir.length-1)
            });
        }
        $scope.dirs = result;
    };
    $scope.opendir = function (dir) {
        if($scope.pre && $scope.pre.dir) {
            $scope.pre.close();
            $('#img-preview').modal('hide');
        }
        $scope.searchList = [];
        if(dir=='') dir='_home';
        $scope.dirType = 0;
        $http.get('/files/open/'+dir+'?sortname='+$scope.sortname+'&sortorder='+$scope.sortorder).success(function (msg) {
            $scope.disk = {limit: byteToStr(msg.disk.limit),used: byteToStr(msg.disk.used),obj:msg.disk};
            $scope.dir = msg.dir ? msg.dir.replace(/\//g,',').replace(/\\/g,',') : '';
            makeDir();
            for(var i=0,l=msg.list.length;i<l;i++){
                var _fileName = msg.list[i].name;
                if($scope.searchName && _fileName.indexOf($scope.searchName)>=0)
                    msg.list[i]._class = 'am-primary';
                if(_fileName.length>18){
                    var _partes = _fileName.split('.');
                    if(msg.list[i].size){
                        msg.list[i].subname = _fileName.substring(0,16)+'***.'+_partes[_partes.length-1];
                    }else{
                        msg.list[i].subname = _fileName.substring(0,16)+'***';
                    }
                }
            }
            $scope.list = msg.list;
        });
    };
    //按类型显示目录下所有文件
    $scope.dirType = '0';
    var findFileByType = function (type) {
        $http.get('/files/searchByType/'+type).success(function (msg) {
            $scope.list = msg;
        })
    };
    $scope.dirTypeChange = function () {
        if($scope.dirType == '0') $scope.refresh();
        else if($scope.dirType == '1'){
            findFileByType('video')
        }else if($scope.dirType == '2'){
            findFileByType('img')
        }
    };
    //刷新当前目录
    $scope.refresh = function () {
        $scope.dirType = '0';
        $scope.searchList = [];
        $scope.opendir('refresh');
    };
    $scope.refresh();
    //打开文件夹或下载文件
    $scope.openFile =function (x, index) {
        if(!x.size) $scope.opendir($scope.dir?$scope.dir+','+x.name:x.name);
        else {
            var suffix = x.name.split('.');
            suffix = suffix[suffix.length-1].toUpperCase();
            if(suffix === 'JPG'||suffix === 'PNG'||suffix === 'GIF')
                $scope.preview(index, x.name,'img');
            else if(suffix === 'MP4')
                $scope.preview(index, x.name, 'video', 'video/mp4');
            else if(suffix === 'AVI' || suffix === 'MKV')
                $scope.preview(index, x.name, 'video');
            else if(suffix === 'TORRENT')
                $scope.startTorrent($scope.dir.replace(/\,/g,'/')+'/'+x.name);
            else{
                messagedelay('暂不支持预览');
            }
        }
    };
    //文件上传
    $scope.openUpload = function () {
        $scope.uploadFiles = [];
        $('#file-upload').modal({width:300,height: 400})
    };
    var form = $('#upload-form');
    var file = form.find('input[type="file"]');
    $scope.select_files = function () {file.click();};
    $scope.upload_files = function () {
        if(!$scope.uploadFiles) return;
        messagealert('文件上传中。。。');
        form.submit();
    };
    file.change(function () {
        var files = file.prop('files');
        $scope.uploadFiles = [];
        for(var i=0,l=files.length;i<l;i++) {
            var size = files[i].size;
            if(size/1000<1) size = size.toFixed(2) + 'B';
            else if(size/1000000<1) size = (size/1000).toFixed(2) + 'KB';
            else size = (size/1000000).toFixed(2) + 'MB';
            $scope.uploadFiles.push({
                name: files[i].name,
                size: size
            });
        }
        $scope.$apply();
    });
    //下载文件
    $scope.download = function (x) {
        if(!x.size && !x.is) return;
        var down_defo = $('#download_deformation');
        down_defo.attr('href','/files/download?dir='+$scope.dir.replace(/\,/g,'/')+'/'+x.name);
        down_defo.find('span').click();
    };
    //在线预览
    $scope.pre ={
        is: false,
        go: function (flag) {
            $scope.pre.index += flag;
            if($scope.pre.index === -1){
                $scope.pre.index = $scope.list.length-1;
            }else if($scope.pre.index === $scope.list.length){
                $scope.pre.index = 0;
            }
            var name = $scope.list[$scope.pre.index].name;
            var suffix = name.split('.');
            suffix = suffix[suffix.length-1].toUpperCase();
            if(suffix === 'JPG'||suffix === 'PNG'||suffix === 'GIF'){
                $scope.preview($scope.pre.index, name, 'img');
            }else{
                $scope.pre.go(flag);
            }
        },
        close: function () {
            $scope.pre.is = false;
            $scope.pre.dir = null;
            $scope.pre.path = null;
            $scope.pre.name = null;
            $scope.pre.src = null;
            $scope.pre.type = null;
        },
        setNowStart: function () {
            $scope.trans.start = parseInt(document.getElementById('priview-video').currentTime);
        },
        setNowEnd: function () {
            $scope.trans.end = parseInt(document.getElementById('priview-video').currentTime);
        }
    };
    $scope.preview = function(index, name, type, srcType){
        var dir = $scope.list[index].dir.replace(/\\/g,',').replace(/\//g,',');
        var path = $scope.list[index].dir.replace(/\,/g,'/') +'/'+name;
        $scope.pre.is= true;
        $scope.pre.dir= dir;
        $scope.pre.index = index;
        $scope.pre.path = path;
        $scope.pre.name = name;
        $scope.pre.src = '/preview'+path;
        $scope.pre.type = type;
        if(type === 'img'){
            $('#img-preview').modal();
            $('#img-preview').on('hide.bs.modal',function () {
                $scope.pre.close();
            });
        }else if(type === 'video'){
            $('#video-preview').modal();
            $('#video-preview').on('hide.bs.modal',function () {
                $scope.pre.close();
            });
            $scope.pre.srcType = srcType;
            $http.post('/transcode/metadata',{name: $scope.pre.name,dir: dir}).success(function (msg) {
                if(isNaN(msg[0].durantion)) {
                    $scope.trans.end = timeToSec(msg[0].tags.DURATION);
                }
                else {
                    $scope.trans.end = parseInt(msg[0].duration );
                }
            })
        }
    };
    //开始转码任务
    $scope.trans = {
        size: 320,
        aspect: '16:9',
        start: 0,
        end: 0
    };
    $scope.transcode = function (list, job) {
        $scope.trans.list = list;
        $scope.trans.job = job;
        $http.post('/transcode',$scope.trans).success(function () {
            messagedelay('已加入队列');
        })

    };
    //开始转换备份的视频
    $scope.backup = function () {
        var list = [];
        $.each($scope.list, function (i, e) {
            if(e.checked) list.push(e)
        });
        if(list.length){
            $http.post('/transcode',{ list: list, job: 'backup'}).success(function () {
                messagedelay('已加入队列');
            })
        }
    };
    //打开Torrent文件，开始BT下载
    $scope.bt = {
        name: null,
        total: null,
        dir: null,
        saveDir: null,
        torrentFiles:[],
        tableDOM: $('#torrent-table'),
        byteToStr: byteToStr,
        download: function(){
            var files = [];
            var tree = $('#torrent-file-tree');
            var nodes = tree.treeview('getSelected');
            if(!nodes.length) {
                erroralert('请选择要下载的文件');
                return;
            }
            $.each(nodes, function (i, e) {
                var path = $scope.bt.name+'/'+e.text;
                $.each($scope.bt.torrentFiles, function (i, t) {
                    if(t.name === e.text) {
                        t.path = path;
                        files.push(t);
                    }
                })
            });
            $http.post('/torrent/BT',{
                name: $scope.bt.name,
                dir: $scope.bt.dir,
                saveDir: $scope.bt.saveDir,
                files: files
            }).success(function () {
                $('#torrent-download').modal('hide');
                messagedelay('已加入下载列表');
            })
        },
        backToLast: function () {
            var temp = $scope.bt.saveDir.split('/');
            if(temp.length === 3) selectDir(',','我的网盘');
            else if(temp.length > 3) {
                var _dir = temp.slice(0,temp.length-2).concat(['']).join(',');
                selectDir(_dir,temp[temp.length-3]);
            }
        }
    };
    var myTreeData = [{}];
    var selectDir = function (dir,name) {
        $scope.bt.saveDir = dir.replace(/\,/g,'/');
        myTreeData = [{
            text: name,
            dir: dir
        }];
        $http.get('/files/dir/'+dir).success(function (msg) {
            myTreeData[0].nodes = [];
            msg.forEach(function (e) {
                myTreeData[0].nodes.push({
                    text: e.name,
                    dir: e.dir
                })
            });
            $('#my-direct-tree').treeview({
                data: myTreeData,
                onNodeSelected: function (event, data) {
                    selectDir(data.dir,data.text);
                }
            });
        });
    };
    $scope.startTorrent = function (dir) {
        selectDir(',','我的网盘');
        $http.put('/torrent/detail',{dir: dir.split('.torrent')[0]}).success(function (msg) {
            $scope.bt.dir = dir;
            $scope.bt.name = msg.name;
            $scope.bt.total = byteToStr(msg.length*1);
            $scope.bt.torrentFiles = msg.files;
            var tree = $('#torrent-file-tree').treeview({
                data: mkTreeByTorrentPath(msg.files),
                multiSelect: true,
                onNodeSelected: function (event, data) {
                    if(data.nodes){
                        $.each(data.nodes,function (i,e) {
                            tree.treeview('selectNode', [ e.nodeId, { silent: true } ]);
                        })
                    }
                },
                onNodeUnselected: function (e, data) {
                    if(data.nodes){
                        $.each(data.nodes,function (i,e) {
                            tree.treeview('unselectNode', [ e.nodeId, { silent: true } ]);
                        })
                    }
                }
            });
            $('#torrent-download').modal();
        })
    }
});

appIndex.controller('offlineController', function($scope, $http){
    $scope.torrentState = torrentState;
    $scope.byteToStr = byteToStr;
    $scope.refresh = function () {
        $http.get('/torrent/status').success(function(msg){
            $scope.status = msg;
            $scope.resumeAble = false;
            $scope.pauseAble = false;
            $scope.deleteAble = false;
        })
    };
    $scope.refresh();
    var changeBtn = function (state) {
        if(state === 0){
            $scope.startAble = false;
            $scope.pauseAble = true;
            $scope.deleteAble = true;
        }else if(state === 1){
            $scope.resumeAble = true;
            $scope.pauseAble = false;
            $scope.deleteAble = true;
        }else if(state === 2){
            $scope.resumeAble = false;
            $scope.pauseAble = false;
            $scope.deleteAble = true;
        }else{
            $scope.resumeAble = false;
            $scope.pauseAble = false;
            $scope.deleteAble = false;
        }
    };
    $scope.chooseOne = function (x) {
        x.checked=!x.checked;
        $scope.status.torrents.forEach(function (t) {
            if(t.infoHash !== x.infoHash) t.checked = false;
        });
        if(x.checked) changeBtn(x.state);
        else changeBtn();
    };
    $scope.resume = function () {
        var torrent;
        $scope.status.torrents.forEach(function (t) {
            if(t.checked && t.state === 1){
                torrent = t;
                $http.put('/torrent/resume',{
                    infoHash: t.infoHash
                }).success(function (msg) {
                    torrent.state = msg.state;
                })
            }
        });
    };
    $scope.pause = function () {
        var torrent;
        $scope.status.torrents.forEach(function (t) {
            if(t.checked && t.state === 0){
                torrent = t;
                $http.put('/torrent/pause',{
                    infoHash: t.infoHash
                }).success(function () {
                    $scope.refresh()
                })
            }
        });
    };
    $scope.delete = function () {
        var torrent;
        $scope.status.torrents.forEach(function (t) {
            if(t.checked && $scope.deleteAble){
                torrent = t;
                $http.put('/torrent/destroy',{
                    infoHash: t.infoHash
                }).success(function () {
                    torrent.state = 3;
                })
            }
        });
    };
    $scope.destroy = function (infoHash) {
        confirmOut('确定要彻底删除改任务？',function () {
            $http.delete('/torrent/'+infoHash).success(function () {
                $scope.refresh();
            });
        })
    };

    var form = $('#upload-form');
    var file = form.find('input[type="file"]');
    $scope.select_files = function () {
        file.click();
    };
    file.change(function () {
        var files = file.prop('files');
        $scope.uploadFiles = '';
        var fileName = files[0].name;
        var strs = fileName.split('.');
        if(strs[strs.length-1] !== 'torrent'){
            erroralert('只支持torrent文件！')
        }else{
            $scope.uploadFiles = fileName;
            setTimeout(function(){
                messagealert('文件上传中。。。');
                $('#add-modal').modal('hide');
                form.submit();
            },50)
        }
        $scope.$apply();
    });
    $scope.input_magnet = function (e) {
        var keycode = window.event?e.keyCode:e.which;
        if(keycode==13){
            $http.put('/torrent/detail',{magnet: $scope.magnet}).success(function (msg) {
                $('#add-modal').modal('hide');
                setTimeout(function () {
                    location.assign('/#/createOfflineMagnet');
                },300);
            })
        }
    };
    $scope.create = function () {
        $('#add-modal').modal();
    }
});

appIndex.controller('transcodeController', function($scope, $http){
    $scope.commandFilter = function(cmd){
        if(cmd === 1) return '转码';
        else if(cmd === 2) return '截图';
    };
    $scope.stateFilter = function (state) {
        var filter = {0:'进行中',1:'错误/未完成',2:'已完成'};
        return filter[state];
    };
    $scope.list = [];
    $scope.refresh = function () {
        $http.get('/transcode/list').success(function(msg){
            $scope.list = msg.rows;
        })
    };
    $scope.refresh();
    $scope.checkAll = function () {
        if($scope.checkedAll){
            $scope.checkedAll = true;
            $.each($scope.list, function (i, e) {
                e.checked = true;
            })
        }else{
            $scope.checkedAll = false;
            $.each($scope.list, function (i, e) {
                e.checked = false;
            })
        }
    };
    $scope.deletable = function () {
        var _deletable = false;
        $.each($scope.list, function (i, e) {
            if(e.checked) _deletable = true;
        });
        return !_deletable;
    };
    $scope.delete = function(){
        var url = '/transcode?workNos=';
        $.each($scope.list, function (i, e) {
            if(e.checked) url+= e.workNo+',';
        });
        $http.delete(url).success(function () {
            $scope.refresh();
            messagedelay('已删除');
        })
    };
    $scope.stopable = function () {
        var _stopable = false;
        for(var i=0 ;i < $scope.list.length; i++){
            var e = $scope.list[i];
            if(e.checked && e.state === 0 && _stopable === false)
                _stopable = true;
            else if (e.checked && e.state !== 0 && _stopable === true){
                return _stopable;
            }
        }
        return !_stopable;
    };
    $scope.stop = function () {
        var workNo=0;
        $.each($scope.list, function (i, e) {
            if(e.checked) workNo = e.workNo;
        });
        $http.put('/transcode/'+workNo).success(function(){
            messagedelay('已停止');
        })
    }
});

appIndex.controller('createOfflineMagnetController', function ($scope, $http) {
    $scope.bt = {
        name: null,
        total: null,
        dir: null,
        saveDir: null,
        torrentFiles:[],
        tableDOM: $('#torrent-table'),
        byteToStr: byteToStr,
        download: function(){
            var files = [];
            /*var tree = $('#torrent-file-tree');
            var nodes = tree.treeview('getSelected');
            if(!nodes.length) {
                erroralert('请选择要下载的文件');
                return;
            }
            $.each(nodes, function (i, e) {
                var path = $scope.bt.name+'/'+e.text;
                $.each($scope.bt.torrentFiles, function (i, t) {
                    if(t.name === e.text) {
                        t.path = path;
                        files.push(t);
                    }
                })
            });*/
            $http.post('/torrent/magnet',{
                name: $scope.bt.name,
                files: files,
                saveDir: $scope.bt.saveDir
            }).success(function () {
                $('#torrent-download').modal('hide');
                messagedelay('已加入下载列表');
            })
        },
        backToLast: function () {
            var temp = $scope.bt.saveDir.split('/');
            if(temp.length === 3) selectDir(',','我的网盘');
            else if(temp.length > 3) {
                var _dir = temp.slice(0,temp.length-2).concat(['']).join(',');
                selectDir(_dir,temp[temp.length-3]);
            }
        }
    };
    var myTreeData = [{}];
    var selectDir = function (dir,name) {
        $scope.bt.saveDir = dir.replace(/\,/g,'/');
        myTreeData = [{
            text: name,
            dir: dir
        }];
        $http.get('/files/dir/'+dir).success(function (msg) {
            myTreeData[0].nodes = [];
            msg.forEach(function (e) {
                myTreeData[0].nodes.push({
                    text: e.name,
                    dir: e.dir
                })
            });
            $('#my-direct-tree').treeview({
                data: myTreeData,
                onNodeSelected: function (event, data) {
                    selectDir(data.dir,data.text);
                }
            });
        });
    };
    $scope.startTorrent = function () {
        selectDir(',','我的网盘');
        $http.get('/torrent/detail').success(function (msg) {
            $scope.bt.name = msg.name;
            $scope.bt.total = byteToStr(msg.length*1);
            $scope.bt.torrentFiles = msg.files;
            /*var tree = $('#torrent-file-tree').treeview({
                data: mkTreeByTorrentPath(msg.files),
                multiSelect: true,
                onNodeSelected: function (event, data) {
                    if(data.nodes){
                        $.each(data.nodes,function (i,e) {
                            tree.treeview('selectNode', [ e.nodeId, { silent: true } ]);
                        })
                    }
                },
                onNodeUnselected: function (e, data) {
                    if(data.nodes){
                        $.each(data.nodes,function (i,e) {
                            tree.treeview('unselectNode', [ e.nodeId, { silent: true } ]);
                        })
                    }
                }
            });*/
        })
    };
    $scope.startTorrent();
});

appIndex.controller('createOfflineBtController', function ($scope, $routeParams, $http) {
    //打开Torrent文件，开始BT下载
    var torrentDir = $routeParams.file;
    $scope.bt = {
        name: null,
        total: null,
        dir: null,
        saveDir: null,
        torrentFiles:[],
        tableDOM: $('#torrent-table'),
        byteToStr: byteToStr,
        download: function(){
            var files = [];
            var tree = $('#torrent-file-tree');
            var nodes = tree.treeview('getSelected');
            if(!nodes.length) {
                erroralert('请选择要下载的文件');
                return;
            }
            $.each(nodes, function (i, e) {
                var path = $scope.bt.name+'/'+e.text;
                $.each($scope.bt.torrentFiles, function (i, t) {
                    if(t.name === e.text) {
                        t.path = path;
                        files.push(t);
                    }
                })
            });
            $http.post('/torrent/BT',{
                name: $scope.bt.name,
                temp: $scope.bt.dir,
                saveDir: $scope.bt.saveDir,
                files: files
            }).success(function () {
                location.assign('/#/offline');
                messagedelay('已加入下载列表');
            })
        },
        backToLast: function () {
            var temp = $scope.bt.saveDir.split('/');
            if(temp.length === 3) selectDir(',','我的网盘');
            else if(temp.length > 3) {
                var _dir = temp.slice(0,temp.length-2).concat(['']).join(',');
                selectDir(_dir,temp[temp.length-3]);
            }
        }
    };
    var myTreeData = [{}];
    var selectDir = function (dir,name) {
        $scope.bt.saveDir = dir.replace(/\,/g,'/');
        myTreeData = [{
            text: name,
            dir: dir
        }];
        $http.get('/files/dir/'+dir).success(function (msg) {
            myTreeData[0].nodes = [];
            msg.forEach(function (e) {
                myTreeData[0].nodes.push({
                    text: e.name,
                    dir: e.dir
                })
            });
            $('#my-direct-tree').treeview({
                data: myTreeData,
                onNodeSelected: function (event, data) {
                    selectDir(data.dir,data.text);
                }
            });
        });
    };
    $scope.startTorrent = function (dir) {
        selectDir(',','我的网盘');
        $http.get('/torrent/detail?dir='+dir.split('.torrent')[0]).success(function (msg) {
            $scope.bt.dir = 'temp/'+dir+'.torrent';
            $scope.bt.name = msg.name;
            $scope.bt.total = byteToStr(msg.length*1);
            $scope.bt.torrentFiles = msg.files;
            var tree = $('#torrent-file-tree').treeview({
                data: mkTreeByTorrentPath(msg.files),
                multiSelect: true,
                onNodeSelected: function (event, data) {
                    if(data.nodes){
                        $.each(data.nodes,function (i,e) {
                            tree.treeview('selectNode', [ e.nodeId, { silent: true } ]);
                        })
                    }
                },
                onNodeUnselected: function (e, data) {
                    if(data.nodes){
                        $.each(data.nodes,function (i,e) {
                            tree.treeview('unselectNode', [ e.nodeId, { silent: true } ]);
                        })
                    }
                }
            });
        })
    };
    $scope.startTorrent(torrentDir);
});

appIndex.controller('liveController', function($scope, $http){
    var body = $('body');
    //直播列表分页
    $scope.page = {
        all: 11,
        offset: 0,
        limit: 10,
        go: function(flag){
            var url = '/live?scape=backup&limit='+this.limit+'&offset=';
            if(flag > 0 && (this.offset + this.limit <= this.all)) {
                url += (this.offset+this.limit);
            }
            else if (flag < 0 && this.offset - this.limit >= 0){
                url += (this.offset-this.limit);
            }else {
                url += 0;
            }
            $http.get(url).success(function(r){
                $scope.page.all = r.count;
                $(r.rows).each(function(i,r){
                    r.dir = r.dir.replace(/\//g,',');
                    r.src = '/live/img?dir='+r.dir+'&name='+r.name;
                });
                $scope.page.list = r.rows;
                $scope.page.offset += $scope.page.limit;
            })
        },
        list: []
    };
    $scope.page.go(1);
    //查看房间
    $scope.houseDetail = function(house, obj) {
        $scope.currentHouse.index = obj;
        if(house.dir) {
            $http.get('/live/allFiles?dir='+house.dir).success(function(r){
                //滚动到视频窗口
                body.animate({scrollTop: $('#live-house').parent().offset().top},1000);
                $scope.currentHouse.poster = '/live/img?dir='+house.dir+'&name='+house.name;
                $scope.currentHouse.options = house;
                if(r.names && r.names.length) {
                    $scope.currentHouse.videos = [];
                    $scope.currentHouse.thumbnails = [];
                    $(r.names).each(function(i, fileName) {
                        if(fileType(fileName) === 'img') {
                            $scope.currentHouse.thumbnails.push({
                                type: fileName.indexOf('thumbnail'),
                                src: '/live/img?dir='+house.dir+'&name='+fileName+'&f=_'+Math.random()*1000
                            })
                        }
                        else if(fileType(fileName) === 'video') {
                            $scope.currentHouse.videos.push({
                                name: fileName
                            })
                        }
                    })
                }
            })
        }
    };
    //直播房间
    $scope.currentHouse = {
        poster: null,
        options: {},
        videos: [],
        index: 0,
        thumbnails: [],
        videoDuration: 0,
        liveAddress: '',
        close: function(){
            var _li = $('#house-list').find('li')[this.index];
            body.animate({scrollTop: $(_li).offset().top},1000);
        },
        open: function(name, seek) {
            $scope.currentHouse.videoDuration = 0;
            $http.get('/live/videoDetail?dir='+this.options.dir+'&name='+name).success(function(r){
                if(isNaN(r.duration) && r.tags.hasOwnProperty('DURATION')) {
                    $scope.currentHouse.videoDuration = timeToSec(r.tags.DURATION);
                }
                else {
                    $scope.currentHouse.videoDuration = r.duration;
                }
                if(!$scope.currentHouse.videoDuration) {
                    erroralert('文件异常');
                    return;
                }
                $http.post('/live/video', {
                    dir: $scope.currentHouse.options.dir,
                    name: name,
                    seek: seek || 0
                }).success(function(v){
                    if(!v.name || !v.host) {
                        erroralert('进入房间失败');
                        return;
                    }
                    var house = $('#live-house');
                    var houseDiv =house .parent();
                    house.height(houseDiv.width()*3/4 + 50);
                    house.width(houseDiv.width());
                    $scope.currentHouse.liveAddress = '/live/house/'+v.name+'?host='+v.host+
                        '&dir='+$scope.currentHouse.options.dir+'&name='+name+'&f=_'+Math.random()*1000;
                });
            })
        }
    }
});